package com.graduation.project.utils;

import cn.hutool.core.util.IdUtil;
import com.graduation.project.entity.other.LoginUser;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

public class FileUtil {

    // 上传文件
    public static void uploadFile(MultipartFile file, String filePath, String fileName) {
        // 拼接上传路径（绝对路径）
        String path = "F:/graduation-project/frontend/graduation-project/" + filePath;
        File uploadFile = new File(path);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        try {
            file.transferTo(new File(uploadFile, fileName));
        }catch (Exception e) {
            throw new RuntimeException("上传失败");
        }
    }

    // 删除文件
    public static void deleteFile(String filePath) {
        // 拼接文件绝对路径
        String absolutePath = "F:/graduation-project/frontend/graduation-project/" + filePath.substring(filePath.indexOf("p"));
        File file = new File(absolutePath);
        if (file.exists()) {
            if (!file.delete()) {
                // 删除失败（文件正在被使用）
                throw new RuntimeException("删除失败,文件正在被使用！");
            }
        } else {
            // 删除文件不存在
            throw new RuntimeException("文件不存在");
        }
    }
}
